// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const managertoolCollection = db.collection('manager_tool')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let managerData

  const mode = event.mode
  const homeText = event.homeText
  const homeConstantTime = event.homeConstantTime
  const homeState = event.homeState
  const userText = event.userText
  const userConstantTime = event.userConstantTime
  const userState = event.userState
  const recommendText1 = event.recommendText1
  const recommendImg1 = event.recommendImg1
  const recommendText2 = event.recommendText2
  const recommendImg2 = event.recommendImg2
  const recommendConstantTime = event.recommendConstantTime
  const recommendState = event.recommendState

  if(mode == 'content'){
    await managertoolCollection.doc('d7cac9a4-2649-4d3b-8fcf-7eaae2902dcd').update({
      data: {
        homeText,
        userText,
        recommendText1,
        recommendImg1,
        recommendText2,
        recommendImg2
      }
    })
  }else{
    await managertoolCollection.doc('d7cac9a4-2649-4d3b-8fcf-7eaae2902dcd').get().then(res => {
      managerData = res.data
    })
    // 只有当按钮状态改变时才对创建时间进行更改
    await managertoolCollection.doc('d7cac9a4-2649-4d3b-8fcf-7eaae2902dcd').update({
      data: managerData.homeState != homeState ? {
        homeConstantTime,
        homeTextCreateDate: new Date().getTime(),
        homeState,
        userConstantTime,
        userState,
        recommendConstantTime,
        recommendState
      } : managerData.userState != userState ? {
        homeConstantTime,
        homeState,
        userConstantTime,
        userTextCreateDate: new Date().getTime(),
        userState,
        recommendConstantTime,
        recommendState
        } : managerData.recommendState != recommendState ? {
            homeConstantTime,
            homeState,
            userConstantTime,
            userState,
            recommendConstantTime,
            recommendCreateDate: new Date().getTime(),
            recommendState
          } : {
              homeConstantTime,
              homeState,
              userConstantTime,
              userState,
              recommendConstantTime,
              recommendState
            }
    })
  }
  
  return {
    event
  }
}